<template>
  <a-drawer
    title="入学参考科目添加"
    :width="windowWidth"
    placement="right"
    :closable="false"
    @close="onClose"
    :visible="referenceManageEditVisiable"
    style="height: calc(100% - 55px);overflow: auto;padding-bottom: 53px;">
    <a-form :form='form'>
      <a-row :gutter="48">
          <a-col :sm="{span:12}" :lg="{span:12}" >
            <a-form-item label="科目码">
              <a-input placeholder="请输入..."  v-decorator="['kmbm',
              {
                rules:[{required:true,message:'请输入科目码'}]
              },
              {initialValue:postParams.kmbm}
              ]"/>
            </a-form-item>
          </a-col>
          <a-col :sm="{span:12}" :lg="{span:12}" >
            <a-form-item label="科目类型">
              <a-select :allowClear="true"  v-decorator="['kmlxm',
              {
                rules:[{required:true,message:'请输入科目类型'}]
              }
              ]">
                <a-select-option v-for="i in TYPE0390" :key="i.id" :value="i.code">{{ i.name }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :sm="{span:12}" :lg="{span:12}"  >
            <a-form-item label="科目名称">
              <a-input placeholder="请输入..."  v-decorator="['kmmc',
              {
                rules:[{required:true,message:'请输入科目名称'}]
              }
              ]"/>
            </a-form-item>
          </a-col>
          <a-col :sm="{span:12}" :lg="{span:12}"  >
            <a-form-item label="所属院系">
              <a-select mode="multiple" optionFilterProp="children" style="width: 100%" :tokenSeparators="[',']" @change="handleChange"  placeholder="请输入..."  v-decorator="['ssyxm',
              {
                rules:[{required:true,message:'请输入所属院系'}]
              }
              ]">
                <a-select-option v-for="i in selectMenu.yx" :key='i.id' :value='i.dwh'>{{i.dwmc}}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>

      </a-row>
      <a-table
        ref="table"
        size="default"
        rowKey="key"
        bordered
        :columns="columns"
        :dataSource="data"
        :pagination="false"
        :scroll="{ x: 1500 }"
        >
        <template v-for="col in ['smmc', 'smzz','cbrq', 'smcbs']" :slot="col" slot-scope="text, record">
          <div :key="col">
            <a-form-item >
            <a-date-picker v-if="col =='cbrq' && text" :format="dateFormat" :defaultValue="moment(text, dateFormat)" @change="(date, dateString) => handlePressChange(record.key,'cbrq',date, dateString)" />
            <a-date-picker v-else-if="col =='cbrq'" :format="dateFormat"  @change="(date, dateString) => handlePressChange(record.key,'cbrq',date, dateString)" />
              <a-input
                style="margin: -5px 0"
                v-else
                :value="text"
                @change="e => handleChange(e.target.value, record.key, col)"

              />
           </a-form-item>
          </div>
        </template>
        <template slot="action" slot-scope="text,record">
          <a @click="handleDelete(record.key)">删除</a>
        </template>
        </a-table>
    </a-form>
    <div style="padding:10px 0;">
      <a-button style="margin-right: .8rem"  type="primary" block @click="handleAddLine">新增行</a-button>
    </div>
    <div class="drawer-bootom-button">
      <a-button style="margin-right: .8rem" @click="onClose">取消</a-button>
      <a-button @click="handleSubmit" type="primary" :loading="loading">保存</a-button>
    </div>
  </a-drawer>
</template>

<script>
import moment from 'moment'
import { STable } from '~'
import { mapState } from 'vuex'
import { constants } from 'fs';
import { type } from 'os';

const formItemLayout = {
  labelCol: { span: 3 },
  wrapperCol: { span: 18 }
}

const selectArr = ['TYPE0126', 'TYPE0075', 'TYPE0125', 'TYPE0072','TYPE0390']
export default {
  name: 'ReferenceManageEdit',
  props: {
    referenceManageEditVisiable: {
      default: false
    },
    info: {
      default: () => []
    }
  },
  components: {
    STable
  },
  data () {
    return {
      dateFormat: 'YYYY-MM-DD HH:mm:ss',
      formItemLayout,
      loading: false,
      windowWidth:"650",
      winWidth:"650",
      data: [],
      postParams: {

      },
      // 表头
      columns: [
        {
          title: '书目名称',
          dataIndex: 'smmc',
          scopedSlots: { customRender: 'smmc' }
        },
        {
          title: '书目作者',
          dataIndex: 'smzz',
          scopedSlots: { customRender: 'smzz' }
        },
        {
          title: '书目出版社',
          dataIndex: 'smcbs',
          scopedSlots: { customRender: 'smcbs' }
        },
        {
          title: '出版日期',
          dataIndex: 'cbrq',
          scopedSlots: { customRender: 'cbrq' }
        },
        {
          title: '操作',
          dataIndex: 'cz',
          fixed: 'right',
          width: 120,
          scopedSlots: { customRender: 'action' }
        }
      ],
      selectMenu: {
        yx: [] // 院系
      },
      details:[]
    }
  },
  beforeCreate(){
    this.form = this.$form.createForm(this)
  },
  computed: {
    ...mapState({
      systemInfo: state => state.app.systemInfo,
      TYPE0126: state => state.app['TYPE0126'], // 年级
      TYPE0390: state => state.app['TYPE0390']
    })
  },
  watch: {
   winWidth(val){
        let that = this
        setTimeout(function(){
          if(val<650){
            that.windowWidth=val
          }else{
            that.windowWidth="650"
          }
        },400)
      },
    info (val) {
      // this.data = this.info.map((e) => {
      //   e.key = Math.random().toString(26).substring(2)
      //   return e
      // })
      this.form.resetFields()
      this.data=val.details;

      val.ssyx=val.ssyxm.split(',')
      console.log(this.data)
       this.postParams = {
        kmbm: val.kmbm,
        kmlxm: val.kmlxm,
        kmmc: val.kmmc,
        ssyxm:val.ssyx,
        id:val.id,
      };
          this.info.ssyxm=this.info.ssyxm.split(',')
       for (let key in this.info) {
        if(key == 'kmbm' || key == 'kmlxm' || key == 'kmmc' || key=='ssyxm' || key == 'id' ){
          this.form.getFieldDecorator(key, {initialValue: this.info[key]})
        }
      }
    }
  },
  mounted(){
    const that=this
     that.windowWidth = document.body.clientWidth>450?450:document.body.clientWidth
    window.onresize=()=>{
      return (()=>{
        window.screenWidth=document.body.clientWidth
        that.winWidth=window.screenWidth
      })()
    }
  },
  created () {
    this.initSelectMenu()
    selectArr.forEach(v => {
      this.$store.dispatch('app/setDictionary', v)
    })
  },
  methods: {
    moment,
    initSelectMenu () {
      let allRequest = [
        this.$api.base.collegeAll()
      ]
      Promise.all(allRequest).then(res => {
        this.selectMenu = {
          yx: res[0].data
        }
      })
    },
    reset () {
      this.data = []
    },
    // 选择院系
    yxChange (code) {
      this.$set(this.queryParam, 'sszym', '')
      this.$set(this.selectMenu,'zy','')
      if(code){
      this.$api.base.majorAll({lsdwh: code}).then(res => {
        this.$set(this.selectMenu, 'zy', res.data)
      })
      }
    },
    handleChange (value, key, column) {
      const newData = [...this.data]
      const target = newData.filter(item => key === item.key)[0]
      if (target) {
        target[column] = value
        this.data = newData
      }
    },
    // 新增行
    handleAddLine () {
      this.data.push({
        smmc: '',
        smzz: '',
        smcbs: '',
        cbrq: '',
        key: Math.random().toString(26).substring(2)
      })
    },
    // 选择招生年度
    zsndChange () {

    },
    // 关闭
    onClose () {
      this.form.resetFields()
      this.$emit('close')
    },
    // 设置时间
    handlePressChange (key, dataIndex, date, dateString) {
      const dataSource = [...this.data]
      const target = dataSource.find(item => item.key === key)
      if (target) {
        target[dataIndex] = dateString
        this.data = dataSource
      }
    },
    // 保存
    handleSubmit () {
      if(typeof(this.postParams.ssyxm)=='object'){
         if(this.postParams.ssyxm.length!=0){
          this.postParams.ssyxm=this.postParams.ssyxm.join(',')
        }
      }
      var flag = true
      this.data.map(item=>{
        if(item.smmc==''){
          this.$message.warning('请输入书目名称')
          this.postParams.ssyxm=this.postParams.ssyxm.split(',')
          flag = false
        }
      })
      if(flag){
          var newObj = this.form.getFieldsValue()
        newObj.ssyxm = newObj.ssyxm.join(',')
        var params = Object.assign(newObj, {
          "details": this.data,
            'id':this.info.id
        })
      // this.reset()
      // this.$emit('success')
      this.form.validateFields( (err,values) => {
        if(err){
          this.$message.warn('请输入必填项')
        }else{
          this.$api.doctorRecruit
            .consultUpdate(params)
            .then(res => {
              this.form.resetFields()
              this.$emit("success");
            })
            .finally(() => {
              this.loadingBtn = false;
              // this.form.resetFields()
            });
        }
      })
      }

    },
    handleDelete (key) {
      const dataSource = [...this.data]
      this.data = dataSource.filter(item => item.key !== key)
    }
  }
}
</script>
